import 'dart:async';

import 'package:flutter/material.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';

class CountDownText extends StatefulWidget {
  CountDownText.toStart({super.key, required this.startTime, this.textStyle})
      : countTime = DateTime.parse(startTime).difference(DateTime.now());
  const CountDownText.count(
      {super.key, required this.countTime, this.textStyle})
      : startTime = "";

  final String startTime;
  final Duration countTime;
  final TextStyle? textStyle;

  @override
  State<CountDownText> createState() => _CountDownTextState();
}

class _CountDownTextState extends State<CountDownText> {
  late Duration count = widget.countTime;
  Timer? timer;
  @override
  void dispose() {
    super.dispose();
    if (timer != null) {
      timer?.cancel();
      timer = null;
    }
  }

  @override
  void initState() {
    timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        count = count - const Duration(seconds: 1);
      });
      if (count.inSeconds == 0) timer.cancel();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return QsText.style(
      count.toString().split(".")[0],
      style: widget.textStyle,
    );
  }
}
